//
//  ProgramaLayout.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/27.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "ProgramaLayout.h"

@interface ProgramaLayout ()
@property (nonatomic,assign) CGFloat yOffset;
@property (nonatomic, retain) NSMutableArray * array;
@end

@implementation ProgramaLayout
- (void)dealloc
{
    [_array release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}
-(void)prepareLayout{
    [super prepareLayout];
    self.yOffset = 0;
    
    NSInteger itemNum = [self.collectionView numberOfItemsInSection:0];
    for (int i=0; i<itemNum; i++) {
        NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        UICollectionViewLayoutAttributes* atts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        // 根据宽高比例计算cell高度
        CGFloat scale = 318.0/190.0; // 图片的实际宽高
        CGFloat imgHeight =  [UIScreen mainScreen].bounds.size.width / 2 / scale;
        
        atts.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2*(i%2) + 1, imgHeight * (i/2)+1, [UIScreen mainScreen].bounds.size.width/2-2, imgHeight-2);
        self.yOffset += atts.frame.size.height/2;
        [self.array addObject:atts];
    }
}
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray * currentArray = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes * atts in _array) {
        if (CGRectIntersectsRect(atts.frame, rect)|| CGRectContainsRect(atts.frame, rect)) {
            [currentArray addObject:atts];
        }
    }
    return currentArray;
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    return [self.array objectAtIndex:indexPath.item];
}
-(CGSize)collectionViewContentSize{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, _yOffset+20);
}
@end
